
import storage from '@system.storage';


const THEME = {
    normal: {
        "0": "#CDC1B4",
        "2": "#EEE4DA",
        "4": "#EDE0C8",
        "8": "#F2B179",
        "16": "#F59563",
        "32": "#F67C5F",
        "64": "#F65E3B",
        "128": "#EDCF72",
        "256": "#EDCC61",
        "512": "#99CC00",
        "1024": "#83AF9B",
        "2048": "#0099CC",
        "2or4": "#645B52",
        "others": "#FFFFFF"
    },
    faded: {
        "0": "#D4C8BD",
        "2": "#EDE3DA",
        "4": "#EDE1D1",
        "8": "#F0CBAA",
        "16": "#F1BC9F",
        "32": "#F1AF9D",
        "64": "#F1A08B",
        "128": "#EDD9A6",
        "256": "#F6E5B0",
        "512": "#CDFF3F",
        "1024": "#CADCD4",
        "2048": "#75DBFF",
        "2or4": "#645B52",
        "others": "#FFFFFF"
    }
};
var colors = THEME.normal;

const SCREEN_WIDTH = 718;
const GRID_WIDTH = 680;
const MARGIN = (SCREEN_WIDTH - GRID_WIDTH) / 2;
const SIDELEN = Math.floor((GRID_WIDTH - MARGIN * 3) / 4);

export default {
    data: {
        bestScores: 0,
        currentScores: 0,
        isShow: false,
        grids : null,
        context: null
    },
    onInit() {
        this.initGrids();

        this.addTwoOrFourToGrids();
        this.addTwoOrFourToGrids();

    },

    onDestroy(){
        console.log('on Destory')
        storage.set({
            key:"bestScores",
            value:this.bestScores.toString(),
            success : ()=>{
                console.log('save bestScores' + this.bestScores);
            },
        })
    },
    onReady(){
        console.log('onReady')
         storage.get({
            key: 'bestScores',
            success: (data)=>{
                this.bestScores = parseInt(data) || 0;
                console.debug('get bestStores ' + data);
            },
             fail: (code,data)=>{
                this.bestScores = 0;
            },
             complete : function(){

             }
        });
    },
    initGrids() {
        this.grids = [[0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0]];
    },
    addTwoOrFourToGrids() {
        let grids = this.grids;
        let array = [];
        for (let row = 0; row < 4; row++) {
            for (let column = 0; column < 4; column++) {
                if (grids[row][column] == 0) {
                    array.push([row, column])
                }
            }
        }
        // array: [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]]

        // Math.random(): [0, 1)之间的小数
        // Math.random() * 16: [0, 16)之间的小数
        // Math.floor(x): 小于等于x的最大整数
        // Math.floor(Math.random() * 16)：[0, 15]之间的整数
        // Math.floor(Math.random() * array.length)：[0, array.length-1]之间的整数
        let randomIndex = Math.floor(Math.random() * array.length);
        let row = array[randomIndex][0];
        let column = array[randomIndex][1];
        if (Math.random() < 0.8) {
            grids[row][column] = 2;
        } else {
            grids[row][column] = 4;
        }


    },

//    onReady() {
//        console.log("onReady" + JSON.stringify(this.$refs.canvas))
//        context = this.$refs.canvas.getContext('2d');
//        if(context == null){
//            console.error('get context error')
//        }
//        console.log("onReady" + JSON.stringify(this.$refs))
//    },

    onCreate(){

        let context = this.context = this.$refs.canvas.getContext('2d');
        if(context == null){
            console.error('get context error')
        }
        else{
            console.error('onCreate ' + JSON.stringify(context))
        }
    },
    onShow() {
        this.drawGrids();
    },
    drawGrids() {
        let grids = this.grids;
        let context = this.context;

        if(context == null){
            context = this.context = this.$refs.canvas.getContext('2d');
        }
        console.log("GRID:" + JSON.stringify(grids));
//        context.clearRect(0,0, GRID_WIDTH,GRID_WIDTH)
        for (let row = 0; row < 4; row++) {
            for (let column = 0; column < 4; column++) {
                let gridStr = grids[row][column].toString();

                context.fillStyle = colors[gridStr];
                let leftTopX = column * (MARGIN + SIDELEN) + MARGIN;
                let leftTopY = row * (MARGIN + SIDELEN) + MARGIN;
                context.fillRect(leftTopX, leftTopY, SIDELEN, SIDELEN);

                context.font = "66px HYQiHei-65S";
                if (gridStr != "0") {
                    if (gridStr == "2" || gridStr == "4") {
                        context.fillStyle = colors["2or4"];
                    } else {
                        context.fillStyle = colors["others"];
                        //context.fillStyle = colors["2or4"];
                    }
                    let offsetX = (4 - gridStr.length) * (SIDELEN / 8);
                    let offsetY = (SIDELEN +45) / 2;
                    context.fillText(gridStr, leftTopX + offsetX, leftTopY + offsetY);
                }
            }
        }

    },
    swipeGrids(event) {
        let context = this.context;
        let grids = this.grids;

        let newGrids = this.changeGrids(event.direction);
        if (newGrids.toString() != grids.toString()) {
            grids = this.grids = newGrids;
            this.addTwoOrFourToGrids();
            this.drawGrids();

            if (this.isGridsFull() == true && this.isGridsNotMergeable() == true) {
                colors = THEME.faded;
                this.drawGrids();
                this.isShow = true;
            }
        }
    },
    isGridsFull() {

        let context = this.context;
        let grids = this.grids;

        if (grids.toString().split(",").indexOf("0") == -1) {
            return true;
        } else {
            return false;
        }
    },
    isGridsNotMergeable() {
        let context = this.context;
        let grids = this.grids;

        for (let row = 0; row < 4; row++) {
            for (let column = 0; column < 4; column++) {
                if (column < 3) {
                    if (grids[row][column] == grids[row][column + 1]) {
                        return false;
                    }
                }
                if (row < 3) {
                    if (grids[row][column] == grids[row + 1][column]) {
                        return false;
                    }
                }
            }
        }
        return true;
    },
    changeGrids(direction) {
        let context = this.context;
        let grids = this.grids;

        let newGrids = [[0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0]];

        if (direction == 'left' || direction == 'right') {
            let step = 1;
            if (direction == 'right') {
                step = -1;
            }

            for (let row = 0; row < 4; row++) {
                let array = [];

                let column = 0;
                if (direction == 'right') {
                    column = 3;
                }

                for (let i = 0; i < 4; i++) {
                    if (grids[row][column] != 0) {
                        array.push(grids[row][column]);
                    }
                    column += step;
                }

                for (let i = 0; i < array.length - 1; i++) {
                    if (array[i] == array[i + 1]) {
                        array[i] += array[i + 1];
                        this.updateCurrentScores(array[i]);
                        array[i + 1] = 0;
                        i++;
                    }
                }

                column = 0;
                if (direction == 'right') {
                    column = 3;
                }

                for (const elem of array) {
                    if (elem != 0) {
                        newGrids[row][column] = elem;
                        column += step;
                    }
                }
            }
        } else if (direction == 'up' || direction == 'down') {
            let step = 1;
            if (direction == 'down') {
                step = -1;
            }

            for (let column = 0; column < 4; column++) {
                let array = [];

                let row = 0;
                if (direction == 'down') {
                    row = 3;
                }

                for (let i = 0; i < 4; i++) {
                    if (grids[row][column] != 0) {
                        array.push(grids[row][column]);
                    }
                    row += step;
                }

                for (let i = 0; i < array.length - 1; i++) {
                    if (array[i] == array[i + 1]) {
                        array[i] += array[i + 1];
                        this.updateCurrentScores(array[i]);
                        array[i + 1] = 0;
                        i++;
                    }
                }

                row = 0;
                if (direction == 'down') {
                    row = 3;
                }

                for (const elem of array) {
                    if (elem != 0) {
                        newGrids[row][column] = elem;
                        row += step;
                    }
                }
            }
        }

        return newGrids;
    },
    updateCurrentScores(gridNum) {
        this.currentScores += gridNum;
        if(this.bestScores < this.currentScores){
            this.bestScores = this.currentScores;
            storage.set({
                key:"bestScores",
                value:this.bestScores.toString(),
                success : ()=>{
                    console.log('save bestScores' + this.bestScores);
                },
                fail: (message,code)=>{
                    console.log('save bestScores error ' + message + this.bestScores);
                }
            })
//            storage.get({
//                key: 'bestScores',
//                success: (data)=>{
//                    console.debug('get bestStores ' + JSON.stringify(data));
//                },
//                fail: (data,code)=>{
//                    this.bestScores = 0;
//                },
//                complete : function(){
//
//                }
//            });
        }
    },
    restartGame() {
        this.currentScores = 0;
        this.isShow = false;
        colors = THEME.normal;

        this.initGrids();

        this.addTwoOrFourToGrids();
        this.addTwoOrFourToGrids();

        this.drawGrids();
    }
}